<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script src="/js/jquery-3.2.1.min.js"></script>
    <script src="/js/bootstrap/bootstrap.min.js"></script>
    <script src="/js/jquery.hammer/hammer.min.js"></script>
    <script src="/js/bootstrap.table/bootstrap-table.min.js" type="text/javascript"></script>
    <script src="/js/bootstrap.table/bootstrap-table-zh-CN.min.js" type="text/javascript"></script>
    <script src="/js/jquery.ztree.all.min.js"></script>
    <script src="/js/dialog.js"></script>
    <script src="/js/comm.js" type="text/javascript"></script>

    <link href="/css/bootstrap/bootstrap.css" rel="stylesheet" />
    <link href="/css/bootstrap.table/bootstrap-table.min.css"/>
    <link href="/css/dialog.css" rel="stylesheet" />
    <link href="/css/zTreeStyle.css" rel="stylesheet" />
    <link href="/css/common.css" rel="stylesheet" />
</head>
<style type="text/css">
    a,a:hover,a:visited,a:link{
        cursor: pointer;
        text-decoration: none;
    }
</style>
<script type="text/javascript">

    var zTreeObj;
    // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
    var setting = {
        async: {
            enable: true,
            type: "post",
            url: "/system/getResourceList.do",
            autoParam: ["id"]
        },
        check: {
            enable: true,
            chkStyle: "checkbox",
            chkboxType: { "Y": "ps", "N": "s" }
        },
        callback: {
            onAsyncSuccess: asyncSuccess
        }
    };

    $(function () {
        //调用函数，初始化表格
        initTable();

        //新增
        $("#btn_add").on("click",function () {
            addRole();
        })

        //删除
        $("#btn_delete").on("click", function () {
            removeRole();
        })

        //修改
        $("#btn_edit").on("click", function () {
            editRole();
        })
    })

    function addRole() {
        var elem = document.getElementById('addEditForm');
        dialog({
            title: "新增角色",
            content: elem,
            width: '50em',
            okValue: "确定",
            ok : function () {
                if(!saveCheckInfo()){
                    return false;
                }
                return saveRoles("add");
            },
            onremove: function () {
                initInput();
            },
            cancelValue: '取消',
            cancel: function () {}
        }).showModal();
    }

    function editRole() {
        var valueInfo = $('#mytab').bootstrapTable('getSelections');
        if(valueInfo!=null&&valueInfo!=""&&valueInfo.length>0){
            $("#code").val(valueInfo[0].code);
            $("#name").val(valueInfo[0].name);
            $("#description").val(valueInfo[0].description);
            $("#status").val(valueInfo[0].status);
            var elem = document.getElementById('addEditForm');

            dialog({
                title: "修改角色",
                content: elem,
                width: '50em',
                okValue: "确定",
                ok : function () {
                    if(!saveCheckInfo()){
                        return false;
                    }
                    return saveRoles("edit",valueInfo[0].id);
                },
                onremove: function () {
                    initInput();
                },
                cancelValue: '取消',
                cancel: function () {}
            }).showModal();
        }else {
            promptDail("请选择一条数据！");
        }
    }

    function removeRole() {
        var valueInfo = $('#mytab').bootstrapTable('getSelections');
        if(valueInfo!=null&&valueInfo!=""&&valueInfo.length>0){

            dialog({
                title: "删除",
                content: "确认删除信息",
                width: '100px',
                okValue: "确定删除",
                ok : function () {
                    var b = false;
                    $.ajax({
                        url: "/system/deleteRole.do",
                        data: {"roleid":valueInfo[0].id},
                        dataType:"json",
                        type:"POST",
                        async: false,
                        success:function (datas) {
                            b = datas.value;
                        }
                    })

                    if(b){
                        promptDail("删除成功！")
                        return true;
                    }else {
                        promptDail("删除失败！")
                        return false;
                    }

                },
                onremove: function () {
                    initTable();
                },
                cancelValue: '取消',
                cancel: function () {}
            }).showModal();
        }else {
            promptDail("请选择一条数据！");
        }
    }




    function initTable() {
        //先销毁表格
        $('#mytab').bootstrapTable('destroy');
        //初始化表格,动态从服务器加载数据
        $("#mytab").bootstrapTable({
            method: "post",  //使用get请求到服务器获取数据
            contentType: "application/x-www-form-urlencoded",
            url: "/system/roleList.do", //获取数据的Servlet地址
            sidePagination: "server", //表示服务端请求
            queryParamsType:'',
            cache: false,
            striped: true,
            queryParams: function queryParams(params) {   //设置查询参数
                var param = {
                    pageNumber: params.pageNumber,
                    pageSize: params.pageSize,
                    name : $("#names").val()
                };
                return param;
            }
        });
    }

    function saveRoles(info, id) {
        var b = false;
        var data = {};
        var url = "";
        data["code"] = $("#code").val();
        data["name"] = $("#name").val();
        data["status"] = $("#status").val();
        data["description"] = $("#description").val();

        if(info=="edit"){
            data["id"] = id;
            url = "/system/editRole.do";
        }else {
            url = "/system/saveRole.do";
        }

        $.ajax({
            url: url,
            data: data,
            dataType:"json",
            type:"POST",
            async: false,
            success:function (datas) {
                b = datas.value;
            }
        })

        if(b){
            promptDail("保存成功！");
            initTable();
        }else {
            promptDail("保存失败！");
        }

        return b;
    }

    //判断是否为空
    function saveCheckInfo(){
        var b = true;
        b = checkValue("name");
        b = checkValue("code");

        return b;
    }

    function editResource(ids) {
        $("#roleIds").val(ids);
        var elem = document.getElementById('editResource');
        zTreeObj = $.fn.zTree.init($("#treeDemo"), setting, null);
        dialog({
            title: "资源管理",
            content: elem,
            width: '250px',
            okValue: "确定",
            ok : function () {
                var nodes = zTreeObj.getCheckedNodes(true);
                if(saveRoleSource(nodes, ids)){
                    promptDail("保存成功!");
                    return true;
                }else {
                    promptDail("保存失败!");
                    return false;
                }

            },
            cancelValue: '取消',
            cancel: function () {}
        }).showModal();

    }

    function saveRoleSource(nodes,ids){
        var data = {};
        var res = "";
        var b = false;
        if(nodes==null||nodes.length<=0){
            return false;
        }
        for(var i=0;i<nodes.length;i++){
            var nodeInfo = nodes[i];
            //只保存子节点
//            if(!nodeInfo.isParent){
//                res +=nodeInfo.id;
//                if(i<nodes.length-1){
//                    res += ",";
//                }
//
//            }
            res +=nodeInfo.id;
            if(i<nodes.length-1){
                res += ",";
            }
        }
        data["roleID"] = ids;
        data["res"] = res;

        $.ajax({
            url: "/system/editRoleSource.do",
            data: data,
            dataType:"json",
            type:"POST",
            async: false,
            success:function (datas) {
                b = datas.value;
            }
        })

        return b;
    }

    //获取资源列表
    function asyncSuccess() {
        $.post("/system/getRoleSource.do",{"roleID":$("#roleIds").val()},function (data) {
            if(data!=null&&data.length>0){
                for(var i=0;i<data.length;i++){
                    var node = zTreeObj.getNodesByParam("id", data[i].sourceid, null);
                    if(node.length>0&&!node[0].isParent){
                        zTreeObj.checkNode(node[0], true, true);
                    }

                }

            }
        },"json")
    }

    function initInput() {
        $("#code").val("");
        $("#name").val("");
        $("#status").val(1);
        $("#description").val("");
    }
</script>
<body style="padding:5px;">
<div class="panel panel-default" >
    <div class="panel-heading">
        查询条件
    </div>
    <div class="panel-body form-group" style="margin-bottom:0px;">
        <form id="searchForm">
        <label class="col-sm-2 control-label" style="width: 10%;text-align: right; margin-top:5px">角色名称：</label>
        <div class="col-sm-2">
            <input type="text" class="form-control" name="names" id="names"/>
        </div>
        <div class="col-sm-1">
            <button class="btn btn-primary" id="search_btn" onclick="initTable();return false;">查询</button>
        </div>
        </form>
    </div>
</div>
<div id="toolbar" class="btn-group pull-right"  style="margin: 0px 0px 5px 0px;">
    <button id="btn_edit" type="button" class="btn btn-default btn-purview" style=" border-radius: 0">
        <span class="glyphicon glyphicon-pencil"  ></span>修改
    </button>
    <button id="btn_delete" type="button" class="btn btn-default btn-purview" >
        <span class="glyphicon glyphicon-remove" ></span>删除
    </button>
    <button id="btn_add" type="button" class="btn btn-default btn-purview">
        <span class="glyphicon glyphicon-plus" ></span>新增
    </button>
</div>
<table id="mytab" data-toggle="table" class="table table-hover table-bordered" data-single-select="true"
       data-toolbar-align="right" data-toolbar="#toolbar" data-pagination="true"  data-page-size="10"
       data-page-list="[10,20,30]" data-pagination-h-align="right" data-pagination-detail-h-align="left"
       data-pagination-loop="false" data-click-to-select="true" >
    <colgroup>
        <col style="width: 5%">
        <col style="width: 10%">
        <col style="width: 20%">
        <col style="width: 15%">
        <col style="width: 20%">
        <col style="width: 20%">
        <col style="width: 10%">
    </colgroup>
    <thead>
        <tr >
            <th data-align="center" data-valign="middle" data-checkbox="true" ></th>
            <th data-align="center" data-valign="middle" data-field="id">id</th>
            <th data-align="center" data-valign="middle" data-field="code">code</th>
            <th data-align="center" data-valign="middle" data-field="name">角色名称</th>
            <th data-align="center" data-valign="middle" data-field="status" data-visible="false">状态</th>
            <th data-align="center" data-valign="middle" data-field="status" data-formatter="initFormat">状态</th>
            <th data-align="center" data-valign="middle" data-field="description">描述</th>
            <th data-align="center" data-valign="middle" data-formatter="initEdit">设置</th>
        </tr>
    </thead>
</table>
<div id="addEditForm" style="display: none;">
    <div style="width: 100%;margin-top: 10px;">
        <form class="form-horizontal" id="nodeForm" role="form">
            <div class="form-group">
                <label class="col-sm-2 control-label">角色编码<span style="color: red;">*</span></label>
                <div class="col-sm-7">
                    <input type="text" class="form-control" id="code" name="code" placeholder="角色编码" onBlur="onBlurValue(this)">
                    <span class="help-block" style="color: red; display: none;">请输入角色编码</span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">角色名称<span style="color: red;">*</span></label>
                <div class="col-sm-7">
                    <input type="text" class="form-control"  id="name" name="name"  placeholder="角色名称" onBlur="onBlurValue(this)">
                    <span class="help-block" style="color: red; display: none;">请输入角色名称</span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">使用状态<span style="color: red;">*</span></label>
                <div class="col-sm-7">
                    <select class="form-control" id="status" name="status" style="width: 30%">
                        <option value="1" >有效</option>
                        <option value="0" >禁用</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">描述</label>
                <div class="col-sm-7">
                    <textarea class="form-control"  id="description" name="description"  placeholder="描述" ></textarea>
                </div>
            </div>
        </form>
    </div>
</div>
<div id="editResource" style="display: none;">
    <div style="width: 100%;margin-top: 10px;">
        <form class="form-horizontal" id="roleForm" role="form">
            <input id="roleIds" name="roleIds" hidden="hidden"/>
            <div style="width: 200px;height: 200px;overflow-y: auto;overflow-x: hidden">
                <ul id="treeDemo" class="ztree" style="width: 200px;height: 200px;">

                </ul>
            </div>
        </form>
    </div>
</div>
</body>
<script style="text/javascript">
    function initFormat(val, row, index) {
        if(val==1||val=="1"){
            return "有效";
        }else {
            return "禁用";
        }
    }

    function initEdit(val, row, index) {
        var html = "<a href='javascript:void(0)' onclick='editResource("+row.id+")'>【设置资源】</a>"
        return html;
    }


</script>
</html>